package com.doublefish.doublefishrobot.ui.setting;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.pdf.PdfRenderer;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.base.BaseActivity;
import com.doublefish.doublefishrobot.ui.setting.adapter.LocalPDFAdapter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class LocalPdfReaderActivity extends BaseActivity {


    @BindView(R.id.tv_title)
    TextView titleTv;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;

    private PdfRenderer pdfRenderer = null;

    private LocalPDFAdapter localPDFAdapter;

    private List<LocalPDFAdapter.LocalPdfBean> list = new ArrayList();

    //跳转
    public static Intent makeIntent(Context packageContext, String name, String title) {
        Intent intent = new Intent(packageContext, LocalPdfReaderActivity.class);
        intent.putExtra("fileName", name);
        intent.putExtra("title", title);
        return intent;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pdf_reader;
    }

    @Override
    protected void initView() {
        localPDFAdapter = new LocalPDFAdapter(this, list);
        localPDFAdapter.setOnGetBitmapCallback(new LocalPDFAdapter.OnGetBitmapCallback() {
            @Override
            public Bitmap onGetBitmap(LocalPDFAdapter.LocalPdfBean pdfBean) {
                int postion = pdfBean.getIndex();
                Bitmap bitmap = readPage(postion);
                if (bitmap != null) {
                    pdfBean.setBitmap(bitmap);
                }
                return bitmap;
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(localPDFAdapter);
    }

    @Override
    protected void initData() {

        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        String name = intent.getStringExtra("fileName");

        titleTv.setText(title);
        getPdfFile(name);
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void onDestroy() {
        realsePdfRenderer();
        super.onDestroy();
    }

    private void getPdfFile(String name) {
        if (TextUtils.isEmpty(name)) {
            return;
        }

        File pdf = new File(getCacheDir(), name);
        if (!pdf.exists()) {
            //本地没有缓存的pdf
            //先把pdf从 assets 写入到缓存
           pdf = writePdfToCahce(name);
           if (pdf == null) {
               showToast("获取隐私政策文件失败，请稍后再试");
               return;
           }
        }
        //生成pdfreader
        createPdfRenderer(pdf);
        if (pdfRenderer != null) {
            //根据pdf的页面生成初始数据
            createList(pdfRenderer.getPageCount());
        }
    }

    private File writePdfToCahce(String name) {
        try {
            InputStream inputStream = getAssets().open(name);
            File file = new File(getCacheDir(), name);
            FileOutputStream outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.close();
            inputStream.close();

            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void createPdfRenderer(File pdfFile) {
        try {
            ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY);
            pdfRenderer = new PdfRenderer(fileDescriptor);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void realsePdfRenderer() {
        if (pdfRenderer != null) {
            pdfRenderer.close();
        }
    }

    private Bitmap readPage(int index) {
        try {
            PdfRenderer.Page page = pdfRenderer.openPage(index);
            //做一个2倍的bitmap
            Bitmap bitmap = Bitmap.createBitmap(page.getWidth() * 2, page.getHeight() * 2, Bitmap.Config.ARGB_8888);
            page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
            page.close();
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //根据pdf的页面生成初始数据
    private void createList(int count) {
        for (int i = 0; i < count; i++) {
            LocalPDFAdapter.LocalPdfBean bean  = new LocalPDFAdapter.LocalPdfBean();
            bean.setIndex(i);
            list.add(bean);
        }
        localPDFAdapter.notifyDataSetChanged();
    }

    @OnClick(R.id.ll_back)
    public void onBackBtnClick() {
        finish();
    }

}
